# -*- coding: utf-8 -*-

'''
/**
 * @file        dpt_main.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2024/05/13
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2024/05/13   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
import argparse

from datetime import datetime
# 获取当前日期
CURR_DATE_STRING = datetime.now().strftime("%Y-%m-%d")
# 获取当前时间
CURR_TIME_STRING = datetime.now().strftime("%H:%M:%S")
## 获取当前脚本所在的目录
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# 输出目录路径
# print("SCRIPT_DIR: "+ SCRIPT_DIR)

sys.path.append(f"{SCRIPT_DIR}/../")

from pyazlib.EasyXlsx import *
from pyazlib.EasyJinja2 import *
from pyazlib.FileSysOpt import *
from dpt_j2_filter_func import *
from dpt_j2_global_func import *


class TDptMsg:

    class TDptData:
        def __init__(self):
            self.数据名称 = ""
            self.数据代码 = ""
            self.数据类型 = ""
            self.数据说明 = ""

    def __init__(self):
        self.消息编号 = 0
        self.消息名称 = ""
        self.消息代码 = ""
        self.消息说明 = ""
        self.data_list = []

def L_DataCellIsNull(cell_data):
    if cell_data == None or cell_data == "":
        return True
    else:
        return False

def L_DataRowIsNull(data_matrix, idx):
    if idx >= len(data_matrix):
        return True
    data_row = data_matrix[idx]
    if (data_row["消息代码"] == None or data_row["消息代码"] == "") and (data_row["数据代码"] == None or data_row["数据代码"] == ""):
        return True
    else:
        return False

def L_DataRowIsMsgDef(data_matrix, idx):
    if idx >= len(data_matrix):
        return False
    data_row = data_matrix[idx]
    if (data_row["消息代码"] != None and data_row["消息代码"] != "") and (data_row["数据代码"] == None or data_row["数据代码"] == ""):
        return True
    else:
        return False

def L_DataRowIsDataDef(data_matrix, idx):
    if idx >= len(data_matrix):
        return False
    data_row = data_matrix[idx]
    if (data_row["消息代码"] == None or data_row["消息代码"] == "") and (data_row["数据代码"] != None and data_row["数据代码"] != ""):
        return True
    else:
        return False

def DptMsgList(data_matrix: list):
    msg_list = []
    i = 0
    while (i < len(data_matrix)):

        if L_DataRowIsNull(data_matrix, i):
            break
        elif L_DataRowIsMsgDef(data_matrix, i):
            msg = TDptMsg()
            msg.消息编号 = data_matrix[i]["消息编号"]
            msg.消息名称 = data_matrix[i]["消息名称"]
            msg.消息代码 = data_matrix[i]["消息代码"]
            msg.消息说明 = data_matrix[i]["消息说明"]
            msg.data_list = []
            
            i += 1
            while (L_DataRowIsDataDef(data_matrix, i)):
                data = TDptMsg.TDptData()
                data.数据名称 = data_matrix[i]["数据名称"]
                data.数据代码 = data_matrix[i]["数据代码"]
                data.数据类型 = data_matrix[i]["数据类型"]
                data.数据说明 = data_matrix[i]["数据说明"]
                data.数据长度 = data_matrix[i]["数据长度"]
                data.数据常量 = data_matrix[i]["数据常量"]
                msg.data_list.append(data)
                i += 1

            msg_list.append(msg)
    
    return msg_list



def DptJ2DictVar(协议概述, 数据矩阵):

    dict_var = {"var_name":"python",
                "var_filename":"dpt_file",
                "var_email":"xxx@hopechart.com",
                "var_date":CURR_DATE_STRING,
                "var_time":CURR_TIME_STRING}

    msg_list = DptMsgList(数据矩阵)
    print(msg_list)

    dict_var["dpt_msg_list"] = msg_list

    dict_var["dpt_brief"] = 协议概述[0]

    return dict_var


def dpt_main(excel_file, output_dir, language_dir):
    ## 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    协议概述 = ReadExcelParamListByColumn(excel_file, "协议概述", title_column_index = 1, start_row = 1) 
    数据矩阵 = ReadExcelParamListByRow(excel_file, "数据矩阵", title_row_index=1, start_col=1)
    language_dir = f"{SCRIPT_DIR}/language/{language_dir}"
    ## 转换模板文件
    # 获取模板文件列表
    j2_file_list = SearchFilesExt(f"{language_dir}/j2_template", ".j2")
    # 获取模板参数字典变量
    j2_dict = DptJ2DictVar(协议概述, 数据矩阵)  

    # 渲染模板文件
    ja2 = TEasyJinja2(f"{language_dir}/j2_template")
    ja2.AddFilterDict(DPT_J2_FILTER_FUNC_DICT)
    ja2.AddGlobalFuncDict(DPT_J2_GLOBAL_FUNC_DICT)

    for j2_file in j2_file_list:
        j2_file_name = os.path.basename(j2_file)
        output_file = f"{协议概述[0]['文件前缀']}_{os.path.splitext(j2_file_name)[0]}"
        j2_dict["var_filename"] = os.path.splitext(os.path.basename(output_file))[0]

        ja2.Render(j2_dict, j2_file_name, f"{output_dir}/{output_file}")

    ## 复制公共文件
    # 获取公共文件列表
    common_file_list = SearchFilesExt(f"{language_dir}/common")
    for filename in common_file_list:
        output_file = os.path.basename(filename)
        CopyFile(f"{language_dir}/common/{filename}", f"{output_dir}/{output_file}")



def create_template(filename):
    #判断输入文件名是否有.xlsx后缀，如果没有则补全
    if not filename.endswith(".xlsx"):
        filename += ".xlsx"
    print("create_template: "+filename)

    tag_dirname = os.path.dirname(filename)
    print("tag_dirname: "+tag_dirname)
    # 实现创建新模板的逻辑
    # 判断filename所在目录是否存在如果不存在则创建
    if tag_dirname != '' and not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    CopyFile(f"{SCRIPT_DIR}/data_protocol_tool.xlsx", filename)
    print("Template creation logic goes here: "+filename)


if __name__ == "__main__":

    # 设置命令行参数解析器
    parser = argparse.ArgumentParser(description='data protocol tool ---- dpt.')

    # -xlsx 参数，变为可选，因为当使用--new时可以忽略
    parser.add_argument('-i','--input', help='Specify the input Excel file path.', default=None)
    
    # -out 参数，同样变为可选
    parser.add_argument('-o','--output', help='Specify the output file path.', default=None)

    # --new 参数，可选参数，创建新模板文件
    parser.add_argument('-n', '--new', help='Create a new template file. Ignores -xlsx and -out.',default=None)

    args = parser.parse_args()

    # 根据--new参数决定是否进行其他参数的验证
    if args.new == None:
        # 验证输入的xlsx文件是否存在
        if args.input and not os.path.isfile(args.input):
            parser.error(f"The file {args.input} does not exist.")
        
        # 验证输出文件路径的目录是否存在
        if args.output and not os.path.exists(os.path.dirname(args.output)):
            # 创建目录
            os.makedirs(os.path.dirname(args.output))
            print(f"Directory {os.path.dirname(args.output)} created.")
    
    print("============= BIGEN: dpt_main.py =============")

    # 根据参数执行相应操作
    if args.new:
        print("Creating a new template. Other parameters ignored.")
        create_template(args.new)
    else:
        print(f"Input file: {args.input}")
        print(f"Output file: {args.output}")

        if args.input != None and args.output != None:
            # 调用dpt_main函数进行处理
            dpt_main(args.input, f"{args.output}/c", 'c')
            dpt_main(args.input, f"{args.output}/python", 'python')
        else:
            print("'dpt -h' for help.")
        


    print("============= END: dpt_main.py =============")



## Generated on "2024-05-13 20:34:13" by the tool "gen_hq_file.py >> V20231119" 

